package objectAdder;

import returnTypes.Size;
import genericObject.GenericObject;
import house.HouseSketch;
import pointAndLine.Point;

public class ObjectAdder {
	private int xIndex,yIndex;
	private int lowerX,upperX;
	private int lowerY,upperY;
	public HouseSketch addObject(GenericObject object, Point centerPoint,HouseSketch house)
	{

		setIndexes(object.getObjectSize(),centerPoint);
		System.out.println(lowerX +" " + lowerY +" "+upperX + " "+ upperY );
		if (checkAvailability(house, centerPoint)) {paint(house, object);}
		else System.out.println("Cannot add object");
		return house;
	}
	
	private boolean checkAvailability(HouseSketch house,Point centerPoint)
	{
		boolean valid=true;
		int owner=house.getMatrixOwnerXY(centerPoint.getCmX(), centerPoint.getCmY());
		for(int x=lowerX;x<=upperX;x++)
			for(int y=lowerY;y<=upperY;y++){
				if (house.getMatrixOwnerXY(x,y)!=owner) { System.out.println("owner fault"); valid=false; break; }
				if (house.getMatrixXY(x, y)!=9) { System.out.println("terrain fault " +house.getMatrixXY(x, y) ); valid=false; break; }
			}				
		return valid;
	}
	
	private void paint(HouseSketch house, GenericObject obj)
	{
		for(int x=lowerX;x<=upperX;x++)
			for(int y=lowerY;y<=upperY;y++)
				house.setMatrixXY(x, y, obj.getCapitation());
	}
	
	private void setIndexes(Size s,Point p)
	{
		Size usageSize=new Size(s,10);
		xIndex=(int)usageSize.getWidth();
		yIndex=(int)usageSize.getLength();
		if( isOdd(xIndex) )
		{
			lowerX=p.getCmX()-xIndex/2;
			upperX=p.getCmX()+xIndex/2;
		}else{
			lowerX=p.getCmX()-xIndex/2;
			upperX=p.getCmX()+xIndex/2-1;
		}
		if( isOdd(yIndex) )
		{
			lowerY=(int)p.getCmY()-xIndex/2;
			upperY=(int)p.getCmY()+xIndex/2;
		}else{
			lowerY=(int)p.getCmY()-xIndex/2;
			upperY=(int)p.getCmY()+xIndex/2-1;
		}

	}
	
	private boolean isOdd(int a)
	{
		if ((a%2)!=0) return true;
		return false;
	}

}
